<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-08-30 10:33:50
-->
<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="850px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '85px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item :label="$t('fleet.vehicleId')" prop="vehicleId">
            <TextInput
              v-model="formData.vehicleId"
              :placeholder="$t('public.pleaseInput')"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item :label="$t('fleet.licensePlate')" prop="vehiclePlate">
            <TextInput
              v-model="formData.vehiclePlate"
              :label="$t('fleet.licensePlate')"
              :maxlength="32"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="props.type === 'edit'" :span="12">
          <el-form-item
            :label="$t('fleet.vehicleStatus')"
            :label-width="language === 'en' ? '180px' : '120px'"
            prop="status"
          >
            <el-radio-group v-model="formData.status">
              <el-radio
                v-for="item in g_options.vehicleStatusOptions"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('fleet.loadCapacity')" prop="seatCount">
            <TextInput
              v-model="formData.seatCount"
              :label="$t('fleet.loadCapacity')"
              :maxlength="4"
              verify-type="nzint"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('fleet.vehicleType')" prop="vehicleType">
            <el-select
              v-model="formData.vehicleType"
              :placeholder="
                g_rules.zhAndEnShowMsg(
                  g_t('public.pleaseSelect'),
                  $t('fleet.vehicleType')
                )
              "
            >
              <el-option
                v-for="item in g_options.vehicleTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('public.location')" prop="regionCode">
            <CascaderArea
              v-model="formData.regionCode"
              :label="$t('public.location')"
              style="width: 100%"
              :level="2"
              @change="handleRegionChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <template #label>
              <label>{{ $t('fleet.vehicleCost') }}</label>
            </template>
            <div class="cost-inline">
              <el-form-item prop="costPerDay">
                <TextInput
                  v-model="formData.costPerDay"
                  :label="$t('fleet.vehicleCost')"
                  verify-type="float"
                  :maxlength="4"
                  @blur="handleInputBlur('costPerDay')"
                >
                  <template #suffix>
                    {{ $t('fleet.yuan') }}/{{ $t('public.sky') }}
                  </template>
                </TextInput>
              </el-form-item>
              <span class="icon">|</span>
              <el-form-item prop="costPerKm">
                <TextInput
                  v-model="formData.costPerKm"
                  :label="$t('fleet.vehicleCost')"
                  verify-type="float"
                  :maxlength="4"
                  @blur="handleInputBlur('costPerKm')"
                >
                  <template #suffix>
                    {{ $t('fleet.yuan') }}/{{ $t('fleet.kilometer') }}
                  </template>
                </TextInput>
              </el-form-item>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('fleet.vehicleRemark')" prop="note">
            <TextInput
              v-model="formData.note"
              type="textarea"
              :rows="2"
              :label="$t('fleet.vehicleRemark')"
            />
          </el-form-item>
        </el-col>
        <el-divider style="margin: 0 0 18px" />
        <el-col :span="12">
          <el-form-item :label="$t('fleet.driver')" prop="driverName">
            <TextInput
              v-model="formData.driverName"
              :label="$t('fleet.driver')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('fleet.gender')"
            :label-width="language === 'en' ? '180px' : '120px'"
            prop="driverSex"
          >
            <el-radio-group v-model="formData.driverSex">
              <el-radio
                v-for="item in g_options.genderOptions"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('fleet.contactPhone')" prop="driverPhone">
            <InputPhone v-model="formData.driverPhone" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="`${$t('fleet.age')}(${$t('fleet.yearsOld')})`"
            :label-width="language === 'en' ? '180px' : '120px'"
            prop="driverAge"
          >
            <TextInput
              v-model="formData.driverAge"
              :label="$t('fleet.age')"
              :maxlength="3"
              verify-type="nzint"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item :label="$t('public.createTime')" prop="createTime">
            <TextInput
              v-model="formData.createTime"
              :minlength="15"
              :maxlength="15"
              :label="$t('public.createTime')"
            />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item :label="$t('fleet.creator')" prop="createBy">
            <TextInput
              v-model="formData.createBy"
              :label="$t('fleet.creator')"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item :label="$t('fleet.idCard')" prop="driverIdNumber">
            <TextInput
              v-model="formData.driverIdNumber"
              :label="$t('fleet.idCard')"
              :minlength="18"
              :maxlength="18"
              verify-type="idcard"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('public.email')"
            :label-width="language === 'en' ? '180px' : '120px'"
            prop="driverEmail"
          >
            <TextInput
              v-model="formData.driverEmail"
              :label="$t('public.email')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('fleet.emergencyContact')"
            prop="emergencyContact"
          >
            <TextInput
              v-model="formData.emergencyContact"
              :label="$t('fleet.emergencyContact')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('fleet.emergencyContactPhone')"
            :label-width="language === 'en' ? '180px' : '120px'"
            prop="emergencyContactPhone"
          >
            <InputPhone
              v-model="formData.emergencyContactPhone"
              :label="$t('fleet.emergencyContactPhone')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
    <!-- <SearchMap
      v-if="searchMapVisible"
      v-model="searchMapVisible"
      :regionName="regionName"
      @add="handleAddRegion"
    /> -->
  </BaseDialog>
</template>

<script setup>
const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  id: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() =>
  props.type === 'add' ? g_t('public.create') : g_t('public.edit')
)

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  vehiclePlate: '',
  // status: '',
  seatCount: '',
  vehicleType: '',
  regionCode: '',
  location: {
    lng: '',
    lat: ''
  },
  costPerDay: '',
  costPerKm: '',
  note: '',
  driverName: '',
  driverSex: '',
  driverPhone: '',
  driverAge: '',
  driverIdNumber: '',
  driverEmail: '',
  emergencyContact: '',
  emergencyContactPhone: ''
})
const rules = {
  vehiclePlate: g_rules.licensePlate,
  status: g_rules.selectRule(g_t('fleet.vehicleStatus')),
  seatCount: g_rules.commonInputText(g_t('fleet.loadCapacity')),
  vehicleType: g_rules.selectRule(g_t('fleet.vehicleType')),
  regionCode: g_rules.selectRule(g_t('public.location')),
  costPerDay: g_rules.vehicleCost,
  costPerKm: g_rules.vehicleCost,
  // note: g_rules.commonInputText(g_t('fleet.vehicleOtherInfoRemark')),
  driverName: g_rules.commonInputText(g_t('fleet.driver')),
  driverSex: g_rules.selectRule(g_t('fleet.gender')),
  driverPhone: g_rules.phone(),
  driverAge: g_rules.age,
  driverIdNumber: g_rules.idCard({
    required: false
  }),
  driverEmail: g_rules.email({
    required: false
  }),
  // emergencyContact: g_rules.commonInputText(g_t('fleet.emergencyContact')),
  emergencyContactPhone: g_rules.phone({
    required: false
  })
}
// const searchMapVisible = ref(false)
// const regionName = ref('')

onMounted(() => {
  props.type === 'edit' && getFormData()
})

const getFormData = () => {
  g_api.fleet
    .apiVehicleDetail({
      id: props.id
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = {
          ...formData.value,
          id: '',
          status: ''
        }
        g_utils.assignFormData(formData.value, data)
        g_utils
          .getAMapLocation(g_utils.getRegionName(data.regionCode))
          .then(data => {
            formData.value.location = data
          })
        console.log('formData.value', formData.value)
      }
    })
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleRegionChange = data => {
  // console.log('handleRegionChange', data)
  formData.value.regionCode = data.lastCode
  g_utils.getAMapLocation(data.text).then(data => {
    formData.value.location = data
  })
}

// const handleMapSelect = _ => {
//   searchMapVisible.value = true
//   // 获取对应类型的区域编码和地址
//   regionName.value = g_utils.getRegionName(formData.value.regionCode, '')
// }

// const handleAddRegion = (type, data) => {
//   // console.log('handleAddRegion', type, data)
//   const { regionCode, lnglat } = data

//   formData.value.regionCode = regionCode[regionCode.length - 1]
//   formData.value.location = {
//     lng: lnglat[0],
//     lat: lnglat[1]
//   }
// }

const handleInputBlur = prop => {
  // 数字化处理
  refDialogForm.value.validateField([prop], vaild => {
    if (vaild && formData.value[prop]) {
      formData.value[prop] = formData.value[prop] * 1
    }
  })
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.fleet.apiVehicleCreate
        : g_api.fleet.apiVehicleUpdate
    urlMethod(formData.value)
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss">
.cost-inline {
  display: inline-flex;
  align-items: center;
  .icon {
    margin: 0 20px;
  }
}
</style>
